<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片内容 -->
    <el-card class="box-card">
      <!-- 搜索和添加 使用布局组件 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <!-- 绑定属性 clearable可清除内容，并触发clear事件重新加载表格数据 -->
          <el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="addDialogVisible">添加</el-button>
        </el-col>
      </el-row>

      <!-- 表格组件 -->
      <template>
        <!-- :data表示绑定数据对象 -->
        <el-table :data="userList" border stripe>
          <el-table-column type="index" label="#"></el-table-column>
          <!-- prop表示数据内容，label为数据名称 -->
          <el-table-column prop="username" label="姓名" width="180"></el-table-column>
          <el-table-column prop="email" label="邮箱" width="180"></el-table-column>
          <el-table-column prop="mobile" label="电话"></el-table-column>
          <el-table-column prop="role_name" label="角色"></el-table-column>
          <el-table-column label="状态">
            <!-- vue2.6以上作用域插槽不知道为什么不会循环，只有一个值 -->
            <!-- <slot :userList="userList">
              {{userList}} 获取得到数据
              <el-switch v-model="mg_state" @change="userStateChanged(mg_state)"></el-switch>
            </slot>-->
            <!-- 旧版操作 -->
            <template slot-scope="scope">
              <!-- {{scope.row}}获取得到数据 -->
              <el-switch v-model="scope.row.mg_state" @change="userStateChanged(scope.row)"></el-switch>
            </template>
          </el-table-column>
          <el-table-column label="操作">
            <template slot-scope="scope">
              <el-row>
                <el-button
                  type="primary"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row.id)"
                  size="small"
                ></el-button>
                <el-button
                  type="danger"
                  icon="el-icon-delete"
                  @click="delRole(scope.row.id)"
                  size="small"
                ></el-button>
                <el-tooltip class="item" effect="dark" content="分配角色" placement="top">
                  <el-button
                    type="warning"
                    icon="el-icon-setting"
                    @click="showRoleDialog(scope.row)"
                    size="small"
                  ></el-button>
                </el-tooltip>
              </el-row>
            </template>
          </el-table-column>
        </el-table>
      </template>

      <!-- 页码区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1,2,5,10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      ></el-pagination>
    </el-card>

    <!-- 添加用户对话框区域 -->
    <el-dialog title="添加用户" :visible.sync="dialogVisible" width="50%" @close="addDialogClosed">
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="addForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="addForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addUser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改用户对话框区域 -->
    <el-dialog title="修改用户" :visible.sync="editDialogVisible" width="50%" @close="editDialogClosed">
      <el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="100px">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="editForm.username"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="editForm.email"></el-input>
        </el-form-item>
        <el-form-item label="电话" prop="mobile">
          <el-input v-model="editForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog title="分配角色" :visible.sync="roleVisible">
      <el-form :model="userInfo">
        <el-form-item label="当前用户名">
          <el-input v-model="userInfo.username" autocomplete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="当前角色">
          <el-input v-model="userInfo.role_name" autocomplete="off" disabled></el-input>
        </el-form-item>
        <el-form-item label="分配新角色">
          <!-- v-model的值与value的值双向绑定 -->
          <el-select v-model="roleId" placeholder="请选择角色">
            <el-option
              v-for="item in roleList"
              :label="item.roleName"
              :value="item.id"
              :key="item.id"
            ></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="roleVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRole">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
export default {
  data() {
    // 添加对话框中邮箱验证规则
    var checkMail = (rule, value, callback) => {
      const regEmail = /^([a-zA-Z0-9_-])+@([a-zA-Z0-9_-])+(\.[a-zA-Z0-9_-])+/
      if (regEmail.test(value)) {
        return callback()
      }
      callback(new Error('请输入正确的邮箱'))
    }
    // 添加对话框中电话验证规则
    var checkMobile = (rule, value, callback) => {
      const regEMobile = /^(0|86|17951)?(13[0-9]|15[012356789]|17[678]|18[0-9]|14[57])[0-9]{8}$/
      if (regEMobile.test(value)) {
        return callback()
      }
      callback(new Error('请输入正确的电话'))
    }
    return {
      // 获取数据所需发送的数据
      queryInfo: {
        query: '',
        // 当前显示页面数
        pagenum: 1,
        // 页面显示数量
        pagesize: 2
      },
      // 获取数据
      userList: [],
      total: 0,
      // 控制添加用户对话框显示
      dialogVisible: false,
      addForm: {
        username: '',
        password: '',
        email: '',
        mobile: ''
      },
      addFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
        ],
        password: [
          { required: true, message: '请输入密码', trigger: 'blur' },
          { min: 6, max: 15, message: '长度在 6 到 15 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkMail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      editDialogVisible: false,
      editForm: {},
      editFormRules: {
        username: [
          { required: true, message: '请输入用户名', trigger: 'blur' },
          { min: 3, max: 8, message: '长度在 3 到 8 个字符', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱', trigger: 'blur' },
          { validator: checkMail, trigger: 'blur' }
        ],
        mobile: [
          { required: true, message: '请输入电话', trigger: 'blur' },
          { validator: checkMobile, trigger: 'blur' }
        ]
      },
      // 分配角色对话框
      roleVisible: false,
      // 当前需分配角色的用户信息
      userInfo: [],
      // 获取角色列表
      roleList: [],
      // 当前选中的角色的id值
      roleId: ''
    }
  },
  created() {
    this.getUserList()
  },
  methods: {
    // 获取表格数据
    async getUserList() {
      const { data: res } = await this.$http.get('users', {
        params: this.queryInfo
      })
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('获取数据列表失败！')
      }
      this.userList = res.data.users
      this.total = res.data.total
    },
    // 页码 显示数量改变触发事件
    handleSizeChange(newSize) {
      // console.log(newSize)
      this.queryInfo.pagesize = newSize
      this.getUserList()
    },
    // 页码改变触发事件
    handleCurrentChange(newSize) {
      this.queryInfo.pagenum = newSize
      this.getUserList()
    },
    // 状态改变触发事件
    async userStateChanged(state) {
      // console.log(state)
      const { data: res } = await this.$http.put(
        `users/${state.id}}/state/${state.mg_state}`
      )
      if (res.meta.status !== 200) {
        state.mg_state = !state.mg_state
        return this.$message.error('用户状态更新失败')
      }
      this.$message.success('更新用户状态成功！')
    },
    // 控制对话框显示
    addDialogVisible() {
      this.dialogVisible = !this.dialogVisible
    },
    // 关闭对话框同时清除表单内容
    addDialogClosed() {
      // console.log(this)
      // this指当前组件
      this.$refs.addFormRef.resetFields()
    },
    // 添加用户
    addUser() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return
        const { data: res } = await this.$http.post('users', this.addForm)
        console.log(res)
        if (res.meta.status !== 201) {
          return this.$message.error('添加用户失败！')
        }
        this.$message.success('添加用户成功！')
        // 将对话框隐藏
        this.dialogVisible = false
        this.getUserList()
      })
    },
    // 修改用户信息
    async showEditDialog(id) {
      const { data: res } = await this.$http.get('users/' + id)
      if (res.meta.status !== 200) {
        return this.$message.error('获取该用户信息失败！')
      }
      this.editForm = res.data
      this.editDialogVisible = !this.editDialogVisible
    },
    // 对话框关闭后重置表单内容
    editDialogClosed() {
      this.$refs.editFormRef.resetFields()
    },
    // 上传修改用户信息
    editUser() {
      this.$refs.editFormRef.validate(async valid => {
        if (!valid) {
          return this.$message.error('请填写完整用户信息')
        }
        const { data: res } = await this.$http.put(
          'users/' + this.editForm.id,
          this.editForm
        )
        if (res.meta.status !== 200) {
          return this.$message.error('修改用户信息失败！')
        }
        this.$message.success('修改用户信息成功！')
        this.editDialogVisible = false
        this.getUserList()
      })
    },
    // 删除用户
    async delRole(id) {
      console.log(id)
      // 弹出确定取消框，是否删除用户
      const confirmResult = await this.$confirm(
        '请问是否要永久删除该用户',
        '删除提示',
        {
          confirmButtonText: '确认删除',
          cancelButtonText: '取消',
          type: 'warning'
        }
      ).catch(err => err)
      // 如果用户点击确认，则confirmResult 为'confirm'
      // 如果用户点击取消, 则confirmResult获取的就是catch的错误消息'cancel'
      if (confirmResult !== 'confirm') {
        return this.$message.info('已经取消删除')
      }
      const { data: res } = await this.$http.delete('users/' + id)
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('删除失败！')
      }
      this.$message.success('删除成功！')
      this.getUserList()
    },
    // 分配角色
    async showRoleDialog(role) {
      this.userInfo = role
      this.roleVisible = true
      const { data: res } = await this.$http.get('roles')
      if (res.meta.status !== 200) {
        return this.$message.error('数据请求失败！')
      }
      this.roleList = res.data
      console.log(res)
    },
    // 保存角色分配信息
    async saveRole() {
      if (!this.roleId) {
        return this.$message.error('请选择修改的角色')
      }
      const { data: res } = await this.$http.put(
        `users/${this.userInfo.id}/role`,
        {
          rid: this.roleId
        }
      )
      if (res.meta.status !== 200) {
        return this.$message.error('角色更新失败！')
      }
      this.$message.success('角色更新成功！')
      this.getUserList()
      this.roleVisible = false
    }
  }
}
</script>

<style lang="less" scoped>
</style>
